package cn.tedu.v3;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 聊天室 Version3
 *
 */
public class Client {
    private Socket socket;
    //1.私有化IP
    private String ip;
    public Client() throws IOException {

try {
    socket = new Socket("172.20.10.3", 1019);
    //2.确定传入IP就是当前就是当前传入ip地址
    ip=socket.getInetAddress().getHostAddress();
  }catch (UnknownHostException e){
    System.out.println("IP地址有问题，请询问服务器端！");
  } catch (IOException e) {
    System.out.println("客户端主动退出了：断开连接");
}
  }
//1.start方法：IO流操作：写出功能，实现读入功能交给线程处理
    public void start(){
        PrintWriter pw=null;
        //BufferedReader bw=null;
        //1.6滞空流赋值 关闭流

        try {
            //1.2读入操作
            BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF8"));
            //1.1写出操作
            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
            //1.3创建线程---Lambda--读入功能--存线程中
            new Thread(()-> {
                //1.4线程中--创建变量--接收服务器端发来的文本
                try {
                String message;
                //1.5一直接收客户端发来的消息:message只要与数据一直输出

                    while ((message = br.readLine()) != null) {//读入服务器端
                        System.out.println("服务器端说：" + message);
                        //1.6 增加一句--每次客户端发给服务器内容
                        System.out.print("客户端请输入：");
                    }
                } catch (IOException e) {
                    System.out.println("客户端发来的消息断开了");
                }
            }).start();


            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("客户端请输入:");
                String say = input.nextLine();
                pw.println("客户端说:"+say);

            }
        }catch (UnsupportedEncodingException e) {
            System.out.println("客户端与服务器端：字符集不一致！");
        }catch (IOException e) {
            System.out.println("客户端断开了连接");
        }finally {
            //关闭流 关闭socket
            if (pw!=null)
                pw.close();
            if (socket!=null&&!socket.isClosed()){
                System.out.println("客户端关闭成功！success!");
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭失败");
                }
            }
        }

    }
    public static void main(String[] args) throws IOException {
        Client client=new Client();
        client.start();
    }
}


